using UnityEditor;
using UnityEngine;
using System.Reflection;
using EntityKit.Runtime;

namespace EntityKit.Editor
{
    [CustomEditor(typeof(EntityComponent<>), true)]
    [CanEditMultipleObjects]
    public class EntityComponentInspector : UnityEditor.Editor
    {
        private bool showEntityInfo = true;
        private FieldInfo ownerField;

        private void OnEnable()
        {
            var memberInfo = target.GetType().BaseType;
            if (memberInfo != null)
                ownerField = memberInfo.GetField("OwnerEntity", BindingFlags.NonPublic | BindingFlags.Instance);
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();
            EditorGUILayout.Space();
            showEntityInfo = EditorGUILayout.Foldout(showEntityInfo, "组件信息", true);
            if (showEntityInfo)
            {
                EditorGUILayout.BeginVertical("box");
                ShowEntityInfo();
                ShowButtons();
                EditorGUILayout.EndVertical();
            }
        }

        private void ShowEntityInfo()
        {
            EditorGUI.indentLevel++;
            DisplayOwnerEntity();
            EditorGUI.indentLevel--;
        }

        private void DisplayOwnerEntity()
        {
            if (ownerField != null)
            {
                var ownerEntity = ownerField.GetValue(target);
                if (ownerEntity != null)
                {
                    EditorGUILayout.LabelField("实体类型: ", ownerEntity.GetType().Name);
                    if (ownerEntity is Object entityObject)
                    {
                        EditorGUILayout.ObjectField("实体对象: ", entityObject, typeof(Object), false);
                    }
                    else
                    {
                        EditorGUILayout.LabelField("实体对象: ", ownerEntity.ToString(), EditorStyles.label);
                    }
                }
                else
                {
                    EditorGUILayout.LabelField("未找到拥有实体", EditorStyles.centeredGreyMiniLabel);
                }
            }
            else
            {
                EditorGUILayout.LabelField("无法访问拥有实体字段", EditorStyles.helpBox);
            }
        }
        

        private void ShowButtons()
        {
            EditorGUILayout.Space();
            GUILayout.BeginHorizontal();
            
            if (GUILayout.Button("刷新"))
            {
                Repaint();
            }
            
            GUILayout.EndHorizontal();
        }
    }
}